package color;
import filter.Function;
import main.Main;

import javax.imageio.ImageIO;
import javax.sound.midi.SysexMessage;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 本类为JFrame的子类，是调色窗口的显示
 */
public class ColorUI extends JFrame implements ActionListener{
    private static final long serialVersionUID = 1L;
    //设置按钮名称
    private static final String CHOOSE = "选择";
    private static final String ChangeColor = "调色";
    private static final String SaveImage = "保存";
    private static final String Return="返回";
    //
    private String sourthPath;
    //设置按钮
    private JButton imgBtn;//选择
    private JButton TS;//调色
    private JButton FH;//返回
    private JButton Save;//保存

    //图片面板
    private ImageJPanel imageJPanel;
    //按钮面板
    private JPanel btnJpanel;
    //原图
    private BufferedImage srcImage;

    /**
     * 构造方法，初始化窗口样式
     */
    public ColorUI(){
        setTitle("调色");
        //选择
        imgBtn = new JButton(CHOOSE);
        //调色
        TS = new JButton(ChangeColor);
        //保存
        Save=new JButton(SaveImage);
        //返回
        FH=new JButton(Return);
        //设置按钮大小
        imgBtn.setPreferredSize(new Dimension(100,40));
        TS.setPreferredSize(new Dimension(100,40));
        Save.setPreferredSize(new Dimension(100,40));
        FH.setPreferredSize(new Dimension(100,40));
        //按钮框
        btnJpanel = new JPanel();
        //设置按钮左对齐
        btnJpanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        //将按钮加入
        btnJpanel.add(imgBtn);
        btnJpanel.add(TS);
        btnJpanel.add(Save);
        btnJpanel.add(FH);
        //图片模块建立
        imageJPanel = new ImageJPanel();
        //将两个模块加入面板
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(imageJPanel,BorderLayout.CENTER);
        getContentPane().add(btnJpanel,BorderLayout.NORTH);
        //设置监听器
        setupActionListener();

    }

    /**
     *设置监听器
     */
    public void setupActionListener(){
        imgBtn.addActionListener(this);
        TS.addActionListener(this);
        Save.addActionListener(this);
        FH.addActionListener(this);
    }
    /**
     * 本方法目的为调整选择的图片的大小，以防过小不便调整，或者过大溢出屏幕，给定选中图片的绝对路径，返回进行大小调整后的图片路径，在本应用中常设调整后的图片为“out.jpg”
     * <p>规定最后大小为长小于等于屏幕的百分之三十，宽小于等于屏幕的百分之六十，其中必有长或宽等于其最大限度值<br>
     * @param from 选中图片的绝对路径
     * @param to 进行大小调整后的图片路径
     */
    public static void adjust(String from, String to) {
        try {
            // 读入文件
            BufferedImage src = ImageIO.read(new File(from));
            // 得到原图宽
            int width = src.getWidth();
            // 得到原图长
            int height = src.getHeight();
            //获取屏幕尺寸
            Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
            //根据长宽分别设置缩放比例
            double scale1=0.3*screenSize.width/width;
            double scale2=0.6*screenSize.height/height;
            //如果按长度缩放比例进行缩放，宽度将大于屏幕的百分之三十，则按宽度缩放比例缩放
            if(scale1>scale2) {
                width = (int) (width * scale2);
                height = (int) (height * scale2);
            }
            //如果按宽度缩放比例进行缩放，长度将大于屏幕的百分之六十，则按长度缩放比例缩放
            else{
                width = (int) (width * scale1);
                height = (int) (height * scale1);
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_DEFAULT);
            BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = result.getGraphics();
            // 绘制缩小后的图
            g.drawImage(image, 0, 0, null);
            g.dispose();
            // 输出到文件流
            ImageIO.write(result, "jpg", new File(to));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 操作
     * @param e 监听事件
     */
    @Override

    public void actionPerformed(ActionEvent e) {
        //报错
        if(SwingUtilities.isEventDispatchThread()){
            System.out.println("Event Dispatch Thred!!");
        }
        //如果选择文件
        if (CHOOSE.equals(e.getActionCommand())){
            //文件选择器
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "图片文件(*.bmp, *.gif, *.jpg, *.jpeg, *.png)", "bmp",
                    "gif", "jpg", "jpeg", "png");
            chooser.setFileFilter(filter);
            chooser.showOpenDialog(null);
            //获取文件（图片）地址
            sourthPath = chooser.getSelectedFile().getAbsolutePath();
            //缩放图片

            adjust(sourthPath,"tmpfiles3.jpg");
            sourthPath="tmpfiles3.jpg";
            try {
                srcImage = ImageIO.read(new File(sourthPath));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            File f = chooser.getSelectedFile();
            //如果成功获取
            if(f != null){
                //设置srcImage
                imageJPanel.setSourceImage(srcImage);//图像面板添加图像
                imageJPanel.setDestImage(srcImage);
                imageJPanel.repaint();
            }

        }
        //如果没有触发选择按钮
        else {
            //如果选择返回 关闭窗口
            if(Return.equals(e.getActionCommand())){
                File file3 = new File("tmpfiles3.jpg");
                //删除中间图片
                if(file3.exists())
                    file3.delete();
                dispose();
                Main.returnFunc();
            }
            //否则如果srcImage为空 提示选择
            else if(srcImage == null){
                JOptionPane.showMessageDialog(this,"请先选择图像源文件");
                return ;

            }
            //如果点击“处理”按钮，则跳出调整图像饱和度，对比度，亮度窗口
            if (ChangeColor.equals(e.getActionCommand())) {
                //调整图像饱和度，对比度，亮度窗口
                final LittleUI bcsUI = new LittleUI(this);
                //点击“确定”按钮，触发事件
                bcsUI.setActionListener(new ActionListener() {
                    //点击确定按钮后执行
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        bcsUI.setVisible(true);
                        //获取原图片的三个属性
                        double s = bcsUI.getSat();
                        double b = bcsUI.getBright();
                        double c = bcsUI.getContrast();
                        bcsUI.dispose();
                        //给deskImage设置
                        imageJPanel.process(new double[]{s, b, c});

                        imageJPanel.repaint();
                    }
                });
                bcsUI.showUI();
                //如果点击“保存”按钮，则跳出保存窗口
            } else if (SaveImage.equals(e.getActionCommand())) {
                // 如果没有对图片进行调整
                if (imageJPanel.getDestImage() == imageJPanel.getSourceImage()) {
                    JOptionPane.showMessageDialog(this, "并未对图片进行更改");
                }
                //图片已经有所调整
                else {
                    //文件选择器
                    JFileChooser chooser = new JFileChooser();
                    FileNameExtensionFilter filter = new FileNameExtensionFilter(
                            "图片文件(*.bmp, *.gif, *.jpg, *.jpeg, *.png)", "bmp",
                            "gif", "jpg", "jpeg", "png");
                    chooser.setFileFilter(filter);
                    //只选择文件
                    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    int option = chooser.showSaveDialog(null);
                    //假如用户选择了保存
                    if (option == JFileChooser.APPROVE_OPTION) {
                        File file = chooser.getSelectedFile();
                        try {
                            //保存
                            ImageIO.write(imageJPanel.getDestImage(), "jpg", file);
                        } catch (IOException ioException) {
                            ioException.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    /**
     * 设置文件过滤器
     * @param chooser 选择器
     */
    public void setFileTypeFilter(JFileChooser chooser){
        FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG & PNG Images","jpg","png");
        chooser.setFileFilter(filter);
    }

    /**
     * 窗口显示
     */
    public void openView(){
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
        pack();
        //显示窗口
        setVisible(true);
        //全屏
        setSize(screenSize.width,screenSize.height-10);
    }

    /**
     * 主函数
     */
    public static void main(){
        ColorUI ui = new ColorUI();
        ui.openView();
    }
}